package com.hzj.controller;

import com.alibaba.fastjson.JSONObject;
import com.hzj.enums.OrderStatusEnum;
import com.hzj.exception.HospitalException;
import com.hzj.helper.HttpRequestHelper;
import com.hzj.pojo.*;
import com.hzj.service.*;
import com.hzj.utils.Result;
import com.hzj.utils.ResultCodeEnum;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@RestController
@RequestMapping("platformapi/order/orderInfo")
public class OrderInfoController {

    @Autowired
    private OrderInfoService ois;
    @Autowired
    HospitalService hs;
    @Autowired
    PatientService ps;
    @Autowired
    MailSend ms;

    @Autowired
    UserService us;

    @Autowired
    RabbitSend rs;


    @PostMapping("/auth/submitOrder/{scheduleId}/{patientId}")
    public Result submitOrder(@PathVariable Integer scheduleId, @PathVariable Integer patientId, HttpServletRequest request) {

        if (StringUtils.isEmpty(scheduleId)) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }
        if (StringUtils.isEmpty(patientId)) {
            throw new HospitalException(ResultCodeEnum.DATA_ERROR);
        }

        //获取就诊人信息
        Patient patient = ps.getById(patientId);

        //获取排班相关信息
        Schedule schedule = hs.getSchedule(scheduleId);

        //获取科室信息
        Department department = hs.getDepartmentByCode(schedule.getDepcode());

//        //判断当前时间是否还可以预约
//        if(new DateTime(schedule.getWorkDate()).isAfterNow()
//                || new DateTime(schedule.getWorkTime()).isBeforeNow()) {
//            throw new HospitalException(ResultCodeEnum.TIME_NO);
//        }

        //获取医院信息
        HospitalInfo hospitalInfo = hs.hospitalByHoscode(schedule.getHoscode());

        //获取医院签名信息
        HospitalSet hospitalSet = hs.getHospitalSetByHoscode(hospitalInfo.getHoscode());

        //添加到订单表
        OrderInfo orderInfo = new OrderInfo();


        orderInfo.setId(Long.valueOf(RandomStringUtils.random(6, false, true)));//生成id


        //scheduleOrderVo 数据复制到 orderInfo
        orderInfo.setHoscode(hospitalInfo.getHoscode());
        orderInfo.setHosname(hospitalInfo.getHosname());
        orderInfo.setDepcode(schedule.getDepcode());
        orderInfo.setDepname(department.getDepname());
        orderInfo.setHosScheduleId(String.valueOf(schedule.getHosScheduleId()));
        orderInfo.setTitle(schedule.getTitle());
        orderInfo.setReserveDate(schedule.getWorkDate());
        //剩余预约数

        orderInfo.setReserveTime(schedule.getWorkTime());
        orderInfo.setAmount(schedule.getAmount());
        //退号时间
        orderInfo.setQuitTime(hospitalInfo.getBookingRule().getQuittime());
//        orderInfo.setOrderStatus();

        //向orderInfo设置其他数据
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);//订单号
//        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());//用户id
        orderInfo.setPatientId(Long.valueOf(patientId));
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //存取订单,改为rabbitmq方式
        rs.saveOrderInfo(orderInfo);

        //调用医院接口，实现预约挂号操作
        //设置调用医院接口需要参数，参数放到map集合
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orderId", orderInfo.getId());
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getHosScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, hospitalSet.getSignKey());
        paramMap.put("sign", sign);
        System.out.println("------" + hospitalSet.getApiUrl() + "/order/submitOrder");
        //请求医院系统接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, hospitalSet.getApiUrl() + "/order/submitOrder");
        System.out.println("==========>>" + result);
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");

            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");

            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //剩余可预约数
            String availableNumber = jsonObject.getString("availableNumber");
            //总共可预约数
            String reservedNumber = jsonObject.getString("reservedNumber");

            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
//            baseMapper.orderInfoUpdateById(orderInfo);


            ois.updateOrderByHosRecordId(orderInfo);




            //发送邮箱提示
            ms.mail(orderInfo,request);

            //修改可预约数
            schedule.setAvailableNumber(Integer.valueOf(availableNumber));
            schedule.setReservedNumber(Integer.valueOf(reservedNumber));
            hs.updateScheduleById(schedule);

        } else {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }


        return Result.ok(orderInfo.getId());
    }

    @PostMapping("/auth/getStatusList")
    public Result getStatusList() {
        return ois.queryOrderInfo();
    }

    @PostMapping("/auth/getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable Long orderId) {
        return Result.ok(ois.queryById(orderId));
    }

    @PostMapping("/auth/cancelOrder/{orderId}")
    public Result cancelOrder(@PathVariable Long orderId) {
        OrderInfo orderInfo = ois.queryById(orderId);

        HospitalSet hospitalSet = hs.getHospitalSetByHoscode(orderInfo.getHoscode());

        Map paramMap = new HashMap();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("hosRecordId", orderInfo.getId());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, hospitalSet.getSignKey());
        paramMap.put("sign", sign);
//        System.out.println("------" + hospitalSet.getApiUrl() + "/order/submitOrder");
        //请求医院系统接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, hospitalSet.getApiUrl() + "/order/updateCancelStatus");
        System.out.println("取消订单返回数据==========>>" + result);
        if (result.getInteger("code") != 200) {
            throw new HospitalException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        //增加预约次数
        boolean b = hs.getScheduleByAddHosScheduleId(orderInfo.getHosScheduleId());
        //删除预约订单
        ois.updateById(orderId);
        if (orderInfo.getOrderStatus() == 1) {
            Result ResultSet = ois.deletePaymentInfo(orderInfo.getOutTradeNo());
            return ResultSet;
        }

        return Result.ok(0);
    }

    @PostMapping("/auth/{page}/{limit}")
    public Result queryByPageLimit(@PathVariable int page, @PathVariable int limit, @RequestParam(required = false) Long patientId, @RequestParam(required = false) Integer orderStatus) {

        return ois.queryByPageLimit(page, limit, patientId, orderStatus);
    }

    @RequestMapping("/rabbittest")
    public String rabbittest(){
        rs.saveOrderInfo(new OrderInfo());
        return "ok";
    }
}
